package com.hyt.it.ogt.kq.common.bm.utils;

import java.net.InetAddress;
import java.util.Set;

import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Sets;

public class UniqueIDUtils {
	private static final Logger logger = LoggerFactory.getLogger(UniqueIDUtils.class);
	public static IdWorker w = null;
	public static long workerId;
	public static long datacenterId;
	static {
		String ip = null;
		try {
			ip = getLocalHostIP();
		} catch (Exception e) {
			logger.error("get ip error :", e);
		}
		logger.info("getLocalHostIP " + ip);
		if (ip != null) {
			String[] ips = ip.split("\\.");
			int ip4 = Integer.parseInt(ips[3]);
			if (ip4 % 2 == 1)
				datacenterId = 1L;
			else
				datacenterId = 2L;
			workerId = datacenterId + 3;
			w = new IdWorker(workerId, datacenterId);
		}
	}

	/**
	 * 获取主键ID
	 * 
	 * @return
	 * @throws Exception
	 */
	public static synchronized long getUniqueID() throws Exception {
		return w.nextId();
	}

	/**
	 * 取本机ip
	 * 
	 * @return
	 * @throws Exception
	 */
	public static String getLocalHostIP() throws Exception {
		InetAddress addr = InetAddress.getLocalHost();
		String ip = addr.getHostAddress();// 获得本机IP
		return ip;
	}

	/**
	 * 生成id
	 * 
	 * @return
	 */
	private static Integer startNum = 0;

	public static synchronized Long generateId() {
		startNum++;
		if (startNum > 9999) {
			startNum = 0;
		}
		String numIndex = "0000";
		if (startNum < 10) {
			numIndex = "000" + startNum;
		} else if (startNum < 100) {
			numIndex = "00" + startNum;
		} else if (startNum < 1000) {
			numIndex = "0" + startNum;
		} else {
			numIndex = startNum.toString();
		}
		try {
			return NumberUtils.createLong(System.currentTimeMillis() + numIndex);
		} catch (Exception e) {
			return NumberUtils.createLong(System.currentTimeMillis() + "0000");
		}
	}

	public static Set<Long> setlist = Sets.newConcurrentHashSet();

	public static void main(String[] args) {
		for (int i = 0; i < 1000; i++) {
			System.out.println(UniqueIDUtils.generateId());
		}
	}
}

class MyThread extends Thread {
	@Override
	public void run() {
		for (int i = 0; i < 10000; i++) {
			UniqueIDUtils.setlist.add(UniqueIDUtils.generateId());
		}
	}
}
